package org.example.authservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import org.example.authservice.mapper.UserMapper;
import org.example.authservice.pojo.*;
import org.example.authservice.service.PermissionService;
import org.example.authservice.service.UserService;
import org.example.authservice.service.impl.UserRoleServiceImpl;
import org.example.authservice.utils.Md5Util;
import org.example.authservice.utils.ThreadLocalUtil;
import org.example.authservice.vo.AssignTreeVO;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @author 张诗琦
 * @since 2024/12/16 11：34
 * @version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleServiceImpl userRoleService;
    @Resource
    private PermissionService permissionService;

    /**
     * 根据用户名或邮箱查询用户
     *
     * @param username 用户名或邮箱
     * @return 用户对象
     */
    @Override
    public User findByUserName(String username) {
        return userMapper.findByUserNameorEmail(username);
    }

    /**
     * 注册用户
     *
     * @param username 用户名
     * @param password 密码
     */
    @Override
    public void register(String username, String password) {
        //加密
        String md5String = Md5Util.getMD5String(password);
        //添加
        userMapper.add(username,md5String);
    }

    /**
     * 查询用户
     *
     * @param username 用户名
     * @return 用户对象
     */
    @Override
    public Integer findIdByUsername(String username) {

        return userMapper.findIdByUsername(username);
    }

    /**
     * 更新用户信息
     *
     * @param user 用户对象
     */
    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    /**
     * 更新头像
     *
     * @param avatarUrl 头像地址
     */
    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl,id);
    }

    /**
     * 更新密码
     *
     * @param newPwd 新密码
     */
    @Override
    public void updatePwd(String newPwd) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updatePwd(Md5Util.getMD5String(newPwd),id);
    }

    /**
     *  保存用户信息
     *
     * @param user 用户对象
     */
    @Transactional
    @Override
    public void saveUser(User user) {
        int i =this.baseMapper.insert(user);
        if(i>0){
            String[] split= user.getRoleId().split(",");
            if(split.length>0){
                List<UserRole> roles= new ArrayList<>();
                for (String s : split) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(Integer.parseInt(s));
                    roles.add(userRole);
                }
                //保存到用户角色表
                userRoleService.saveBatch(roles);
            }
        }
    }

    /**
     * 编辑用户信息
     *
     * @param user 用户对象
     */
    @Override
    @Transactional
    public void editUser(User user) {
        int i =this.baseMapper.updateById(user);
        if(i>0){
            String[] split= user.getRoleId().split(",");
            //删除用户原来的角色
            QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(UserRole::getUserId,user.getId());
            userRoleService.remove(queryWrapper);
            //重新创建
            if(split.length>0){
                List<UserRole> roles= new ArrayList<>();
                for (String s : split) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(Integer.parseInt(s));
                    roles.add(userRole);
                }
                //保存到用户角色表
                userRoleService.saveBatch(roles);
            }
        }
    }

    /**
     * 删除用户
     *
     * @param id 用户id
     */
    @Override
    @Transactional
    public void deleteUser(Integer id) {
        //删除用户
        int i =this.baseMapper.deleteById(id);
        if(i>0){
            //删除用户角色
            QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(UserRole::getUserId,id);
            userRoleService.remove(queryWrapper);
        }
    }

    /**
     * 查询用户角色
     *
     * @param parm 查询参数
     * @return 角色id数组
     */
    @Override
    public AssignTreeVO getAssignTree(AssignTreeParm parm) {
        //查询用户信息
        List<Permission> permissionList;
        this.baseMapper.selectById(parm.getUserId());
        permissionList = permissionService.list();
        //组装树
        List<Permission> makeTree = MakeMenuTree.makeTree(permissionList,0);
        //查询角色原来的菜单
        List<Permission> roleList = permissionService.getPermissionByRoleId(parm.getRoleId());
        List<Integer> ids = new ArrayList<>();
        Optional.ofNullable(roleList).orElse(new ArrayList<>())
                .stream()
                .filter(Objects::nonNull)
                .forEach(item -> ids.add(item.getId()));
        //组装返回的数据
        AssignTreeVO vo =new AssignTreeVO();
        vo.setCheckList(ids.toArray());
        vo.setPermissionList(makeTree);
        return vo;
    }

    /**
     * 重置密码
     *
     * @param email 邮箱
     * @param newPwd 新密码
     */
    @Override
    public void updateforgotPwd(String email, String newPwd) {
        userMapper.updateforgotPwd(email,Md5Util.getMD5String(newPwd));
    }

    /**
     * 根据输入查询用户
     *
     * @param inputvalue 输入值
     * @return 用户对象
     */
    @Override
    public User findByInput(String inputvalue) {
        return userMapper.findByInput(inputvalue);
    }


}
